<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeFn"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :data="depts"
          :props="defaultProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          :highlight-current="true"
          node-key="id"
        ></el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            size="mini"
            type="primary"
            v-permission="`add-employee`"
            @click="$router.push('/employee/detail')"
            >添加员工</el-button
          >
          <el-button size="mini" @click="showExcelDialog = true"
            >excel导入</el-button
          >
          <el-button size="mini" @click="exportEmployExcel"
            >excel导出</el-button
          >
        </el-row>
        <!-- 表格组件 -->
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :size="30"
                :src="row.staffPhoto"
              ></el-avatar>
              <span class="username" v-else>{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="mobile" width="120px" sortable label="手机号">
          </el-table-column>
          <el-table-column
            prop="workNumber"
            width="120px"
            sortable
            label="工号"
          >
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span>{{
                row.formOfEmployment === 1
                  ? "正式"
                  : row.formOfEmployment === 2
                  ? "非正式"
                  : "无"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门">
          </el-table-column>
          <el-table-column prop="timeOfEntry" sortable label="入职时间">
          </el-table-column>
          <el-table-column width="200px" label="操作">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="mini"
                @click="$router.push(`/employee/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button
                type="text"
                size="mini"
                style="margin-right: 10px"
                @click="getRoleInfo(row.id)"
                >角色</el-button
              >
              <el-popconfirm
                title="确定要删除此角色吗？"
                @onConfirm="deleteFn(row.id)"
              >
                <el-button slot="reference" type="text" size="mini"
                v-permission="`del-employee`"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            @current-change="getEmployee"
            :current-page.sync="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </div>
      <import-excel :showExcelDialog.sync="showExcelDialog" />
      <!-- 分配角色弹窗 -->
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <el-checkbox-group v-model="roleIds">
          <el-checkbox
            v-for="item in roleList"
            :key="item.key"
            :label="item.id"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="confirmRole"
              >确定</el-button
            >
            <el-button size="mini" @click="showRoleDialog = false"
              >取消</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDepartmentsApi } from "@/api/department";
import {
  getEmployeeApi,
  exportEmployExcelApi,
  delEmployeeApi,
  getEnabledRoleListApi,
  getEmployeeInfoApi,
  assignRoleApi,
} from "@/api/employee";
import { transListToTree } from "@/utils/index";
import ImportExcel from "@/views/employee/components/ImportExcel.vue";
import FileSaver from "file-saver";
export default {
  name: "Employee",
  components: {
    ImportExcel,
  },
  data() {
    return {
      depts: [],
      tableData: [],
      roleList: [],
      roleIds: [],
      loading: false,
      currentId: null,
      defaultProps: {
        children: "children",
        label: "name",
      },
      total: 0,
      showExcelDialog: false,
      showRoleDialog: false,
      // 请求员工列表参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: "",
      },
    };
  },
  created() {
    this.getDepts();
    this.getEnabledRoleList();
  },
  methods: {
    // 左树  获取部门列表
    async getDepts() {
      const res = await getDepartmentsApi();
      this.depts = transListToTree(res, 0);
      this.queryParams.departmentId = this.depts[0].id;
      // vue 更新 dom 是异步的，直接调用的时候页面还没有渲染树，不起效果
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId);
      });
      this.getEmployee();
    },
    // 右表 获取员工列表
    async getEmployee() {
      const res = await getEmployeeApi(this.queryParams);
      this.tableData = res.rows;
      this.total = res.total;
    },
    // 点击部门获取对应员工列表
    handleNodeClick(current) {
      this.queryParams.departmentId = current.id;
      this.queryParams.page = 1; // 设置成第一页再请求
      this.getEmployee();
    },
    // 模糊搜索，防抖
    changeFn() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.queryParams.page = 1;
        this.getEmployee();
      }, 500);
    },
    // 导出excel 员工信息表
    async exportEmployExcel() {
      const res = await exportEmployExcelApi();
      FileSaver.saveAs(res, "员工信息表.xlsx");
    },
    // 删除
    async deleteFn(id) {
      await delEmployeeApi(id);
      this.$message.success("删除成功");
      if (this.tableData.length === 1 && this.queryParams.page > 1)
        this.queryParams.page--;
      this.getEmployee();
    },
    async getEnabledRoleList() {
      this.roleList = await getEnabledRoleListApi();
    },
    // 角色数据回显
    async getRoleInfo(id) {
      try {
        this.loading = true;
        this.currentId = id;
        const res = await getEmployeeInfoApi(id);
        this.roleIds = res.roleIds;
        this.showRoleDialog = true;
      } finally {
        this.loading = false;
      }
    },
    // 分配角色
    async confirmRole() {
      await assignRoleApi({id:this.currentId,roleIds:this.roleIds});
      this.$message.success('分配权限成功')
      this.showRoleDialog = false
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
